package com.ncmmall.api.apis.mall.live;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ncmmall.api.apis.mall.live.model.VideoRecordCallback;
import com.ncmmall.api.apis.service.Result;
import com.ncmmall.api.security.Securitys;
import com.ncmmall.application.business.live.LiveApplication;
import com.ncmmall.application.business.live.LiveSessionApplication;
import com.ncmmall.application.business.live.tencentcloud.im.IMUtils;
import com.feijin.commons.lang.PropertiesHelps;
import com.feijin.commons.lang.Requires;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.live.LiveFans;
import com.ncmmall.domain.business.live.LiveSession;
import com.ncmmall.domain.business.live.LiveSessionGoods;
import com.ncmmall.domain.business.live.LiveSessionRecord;
import com.ncmmall.domain.business.live.LiveSessionRedpacket;
import com.ncmmall.domain.business.live.QLiveSession;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import static java.util.stream.Collectors.toList;

/**
 * 直播间接口（直播间内部操作）
 *
 * @author likaikai
 * @date 2020-10-30 17:43:27
 */
@RestController
@RequestMapping("/live/session")
@Slf4j
@RequiredArgsConstructor
public class LiveSessionApi {

    private static final String STORE_DOMAIN = PropertiesHelps.getValue("store.domain");
    private final QueryChannelService queryChannelService;
    private final LiveApplication liveApplication;
    private final LiveSessionApplication liveSessionApplication;

    /**
     * 开始直播
     */
    @PostMapping("/start")
    public Result start(HttpServletRequest request, @RequestBody LiveSession params) {

        Result result = new Result();
        try {
            WebUser anchor = Securitys.user(request);
            LiveApplication.requireUserIsAnchor(anchor);

            liveSessionApplication.start(anchor, params);
            return result.ok();

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[开始直播异常]", e);
            return result.fail().setMsg("开始直播异常");
        }
    }

    /**
     * 结束直播(只有主播自己能结束直播)
     */
    @PostMapping("/end")
    public Result end(HttpServletRequest request) {

        Result result = new Result();
        try {

            WebUser anchor = Securitys.user(request);
            LiveApplication.requireUserIsAnchor(anchor);

            liveSessionApplication.end(anchor);
            return result.ok();

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[结束直播异常]", e);
            return result.fail().setMsg("结束直播异常");
        }
    }

    /**
     * 关注主播
     */
    @PostMapping("/attention")
    public Result attentionAnchor(HttpServletRequest request, @RequestBody LiveFans params) {

        Result result = new Result();
        try {
            Requires.isTrue(params.getId() > 0, "直播间id不正确");
            LiveSession liveSession = queryChannelService.findOne(LiveSession.class, params.getId());
            Requires.notNull(liveSession, "直播间不存在");

            boolean b = liveApplication.attentionAnchor(liveSession.getAnchor(), Securitys.user(request));
            return result.ok().inject(ImmutableMap.of("status", b));

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[关注主播异常]", e);
            return result.fail().setMsg("操作异常");
        }
    }

    /**
     * 直播历史列表
     */
    @GetMapping("/list")
    public Result historyList(HttpServletRequest request, QueryPageRequest pageRequest) {
        Result result = new Result();
        try {
            WebUser user = Securitys.user(request);
            LiveApplication.requireUserIsAnchor(user);

            QueryPage<LiveSessionRecord> page = queryChannelService.findPage("select r from LiveSessionRecord r where r.liveSession.anchor.id = :aid order by r.id desc",
                    pageRequest.setParams(ImmutableMap.of("aid", user.getId())), LiveSessionRecord.class);

            List<Map<String, Object>> list = page.getResult().stream()
                    .map(r -> {
                        LiveSession s = r.getLiveSession();
                        Map<String, Object> map = new TreeMap<>();
                        map.put("image", STORE_DOMAIN + "/uploads/" + s.getImage());
                        map.put("name", s.getName());
                        map.put("beginTime", DateUtil.format(r.getStartTime(), "yyyy/MM/dd HH:mm"));
                        map.put("endTime", DateUtil.format(r.getEndTime(), "yyyy/MM/dd HH:mm"));
                        map.put("videoUrl", r.getVideoUrl());
                        map.put("id", s.getId());
                        return map;
                    })
                    .collect(toList());

            return result.ok().inject(ImmutableMap.of("page", new QueryPage<>(page.getTotalCount(), list, pageRequest.getPageNo(), pageRequest.getPageSize())));

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[获取直播历史异常]", e);
            return result.fail().setMsg("获取数据异常");
        }
    }

    /**
     * 移除直播记录
     *
     * @param id 直播场次id
     */
    @DeleteMapping("/remove")
    public Result remove(long id, HttpServletRequest request) {
        Result result = new Result();
        try {
            WebUser user = Securitys.user(request);
            LiveApplication.requireUserIsAnchor(user);

            LiveSession liveSession = queryChannelService.findOne(QLiveSession.liveSession.id.eq(id).and(QLiveSession.liveSession.anchor.id.eq(user.getId())), LiveSession.class);
            Requires.notNull(liveSession, "直播记录不存在");

            liveSessionApplication.remove(liveSession);
            return result.ok();

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[删除直播记录异常]", e);
            return result.fail().setMsg("删除异常");
        }
    }

    /**
     * 直播详情
     *
     * @param id     直播场次ID
     * @param liveID 主播房间号ID
     */
    @GetMapping("/detail")
    public Result liveDetail(HttpServletRequest request, Long id, String liveID) {

        Result result = new Result();
        try {

            LiveSession liveSession = null;
            if (id != null) {
                liveSession = queryChannelService.findOne(LiveSession.class, id);
            } else if (StrUtil.isNotBlank(liveID)) {
                WebUser user = queryChannelService.findOne(QWebUser.webUser.liveID.eq(liveID).and(QWebUser.webUser.liveType.eq(1)), WebUser.class);
                Requires.notNull(user, "主播不存在");
                liveSession = queryChannelService.queryOneEntity("select * from live_session where remove = false and anchor_id = :aid order by id desc",
                        ImmutableMap.of("aid", user.getId()), LiveSession.class);
            }
            Requires.isTrue(liveSession != null && liveSession.getEndTime() == null, "主播未开播");

            WebUser anchor = liveSession.getAnchor();
            Map<String, Object> map = new TreeMap<>();
            map.put("id", liveSession.getId());
            map.put("anchorAvatar", STORE_DOMAIN + "/avatar/" + anchor.getAvatar());
            map.put("anchorName", anchor.getNickname());
            map.put("anchorId", anchor.getId());
            map.put("lookNumber", liveSession.getLookNumber());
            map.put("likeNumber", liveSession.getLikeNumber());
            map.put("liveID", anchor.getLiveID());
            map.put("playUrl", liveSession.getPlayUrl());

            LiveSessionGoods sessionGoods = liveSession.getCurrentGoods();
            if (sessionGoods != null) {
                map.put("currentGoods", liveGoods(sessionGoods));
            } else {
                map.put("currentGoods", null);
            }

            WebUser user = Securitys.user(request);
            if (user.getId() == anchor.getId()) {
                //主播本人,返回推流地址，当前直播商品数据
                map.put("pushUrl", liveSession.getPushUrl());

            } else {
                long number = liveSessionApplication.look(liveSession);
                map.put("lookNumber", number);
            }
            map.put("imGroupId", liveSession.getImGroupId());

            //是否关注主播
            int count = queryChannelService.selectCount("select count(*) from live_fans where anchor_id = :aid and fans_id = :fid",
                    ImmutableMap.of("aid", anchor.getId(), "fid", user.getId()));
            map.put("focus", count > 0);

            //todo 助理提示
            return result.ok().inject(map);

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[获取直播详情异常]", e);
            return result.fail().setMsg("获取数据异常");
        }
    }

    /**
     * 直播录制回调
     */
    @RequestMapping("/record/callback")
    public Map<String, Integer> recordCallback(@RequestBody VideoRecordCallback callback) {

        Map<String, Integer> res = new HashMap<>();
        res.put("code", 0);

        try {
            if (callback.getEventType() != 100) {
                return res;
            }
            if (StringUtils.isBlank(callback.getVideoUrl())) {
                return res;
            }
            if (!LiveSessionApplication.checkRecordCallbackSign(callback.getSign(), callback.getT())) {
                return res;
            }
            LiveSession liveSession = queryChannelService.findOne(QLiveSession.liveSession.id.eq(Long.parseLong(callback.getStreamId())), LiveSession.class);
            if (liveSession == null) {
                return res;
            }

            log.info("直播录制回调：{}", callback);

            LiveSessionRecord record = new LiveSessionRecord();
            record.setLiveSession(liveSession);
            record.setVideoUrl(callback.getVideoUrl());
            record.setStartTime(new Timestamp(callback.getStartTime() * 1000));
            record.setEndTime(new Timestamp(callback.getEndTime() * 1000));
            record.setDuration(callback.getDuration());
            record.setFileSize(callback.getFileSize());
            liveSessionApplication.recordCallback(record);
            return res;

        } catch (Exception e) {
            log.error("[直播录制回调异常]", e);
            return res;
        }
    }

    /**
     * 主播切换下一件商品
     */
    @GetMapping("/nextGoods")
    public Result nextGoods(HttpServletRequest request) {

        Result result = new Result();
        try {
            WebUser anchor = Securitys.user(request);
            LiveApplication.requireUserIsAnchor(anchor);
            Requires.isTrue(anchor.isLiveStatus() && anchor.getLiveSession() != null, "当前未直播");

            LiveSessionGoods sessionGoods = liveSessionApplication.nextGoods(anchor);

            Map<String, Object> map = new TreeMap<>();
            if (sessionGoods != null) {
                map.put("currentGoods", liveGoods(sessionGoods));
            } else {
                map.put("currentGoods", null);
            }
            return result.ok().inject(map);

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[直播切换商品异常]", e);
            return result.fail().setMsg("切换异常");
        }
    }

    /**
     * 封装直播间商品
     *
     * @param sessionGoods 当前直播商品
     */
    private Map<String, Object> liveGoods(LiveSessionGoods sessionGoods) {
        Map<String, Object> currentGoods = new TreeMap<>();
        Goods goods = sessionGoods.getGoods();
        currentGoods.put("goodsName", goods.getName());
        currentGoods.put("price", goods.getDefaultPrice());
        currentGoods.put("image", STORE_DOMAIN + "/uploads/" + goods.getDefaultImage());
        currentGoods.put("id", sessionGoods.getId());
        currentGoods.put("goodsId", goods.getId());
        currentGoods.put("store", goods.getStore());
        return currentGoods;
    }

    /**
     * 定时更新直播间数据
     *
     * @param id 直播id
     */
    @GetMapping("/liveUpdate")
    public Result liveUpdate(long id) {

        Result result = new Result();
        try {

            LiveSession session = queryChannelService.findOne(LiveSession.class, id);
            Requires.isTrue(session != null && session.getEndTime() == null, "直播不存在");

            LiveSessionGoods sessionGoods = session.getCurrentGoods();
            Map<String, Object> map = new TreeMap<>();

            if (sessionGoods != null) {
                map.put("currentGoods", liveGoods(sessionGoods));
            } else {
                map.put("currentGoods", null);
            }

            map.put("likeNumber", session.getLikeNumber());
            map.put("lookNumber", session.getLookNumber());

            return result.ok().inject(map);

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[获取直播间数据异常]", e);
            return result.fail().setMsg("获取数据异常");
        }
    }

    /**
     * 游客获取直播间当前直播商品列表
     *
     * @param id 直播id
     */
    @GetMapping("/currentGoodsList")
    public Result currentGoodsList(long id) {
        Result result = new Result();
        try {
            LiveSession session = queryChannelService.findOne(LiveSession.class, id);
            Requires.isTrue(session != null && session.getEndTime() == null, "直播不存在");

            List<LiveSessionGoods> goods = queryChannelService.findAll("from LiveSessionGoods g where g.liveSession.id = :sid and g.status = true order by g.id asc",
                    ImmutableMap.of("sid", id), LiveSessionGoods.class);

            List<Map<String, Object>> list = goods.stream().map(this::liveGoods).collect(toList());
            return result.ok().inject(ImmutableMap.of("list", list));

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[获取直播间商品列表异常]", e);
            return result.fail().setMsg("获取数据异常");
        }
    }

    /**
     * 直播间点赞
     *
     * @param id 直播id
     */
    @GetMapping("/like")
    public Result like(long id) {
        Result result = new Result();
        try {
            LiveSession session = queryChannelService.findOne(LiveSession.class, id);
            Requires.isTrue(session != null && session.getEndTime() == null, "直播不存在");

            long number = liveSessionApplication.like(session);
            return result.ok().inject(ImmutableMap.of("likeNumber", number));

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[直播间点赞异常]", e);
            return result.fail().setMsg("点赞异常");
        }
    }

    /**
     * 获取im用户签名
     *
     * @param id 直播id
     */
    @GetMapping("/imSign")
    public Result imSign(HttpServletRequest request, long id) {
        Result result = new Result();
        try {

            LiveSession session = liveSessionApplication.findById(id);
            Requires.isTrue(session != null && session.getEndTime() == null, "直播不存在");

            String sign;
            long anchorId = session.getAnchor().getId();
            WebUser user = Securitys.user(request);
            if (anchorId == user.getId() || (user.getAnchor() != null && anchorId == user.getAnchor().getId())) {
                sign = IMUtils.generateUserSign(IMUtils.ADMIN_ACCOUNT);
                return result.ok().inject(ImmutableMap.of("sign", sign, "userId", IMUtils.ADMIN_ACCOUNT));
            } else {
                sign = IMUtils.generateUserSign(String.valueOf(user.getId()));
                return result.ok().inject(ImmutableMap.of("sign", sign, "userId", user.getId()));
            }
        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[获取im签名异常]", e);
            return result.fail().setMsg("获取数据异常");
        }
    }

    /**
     * 用户禁言, 主播或者助理才能调用
     *
     * @param id     直播id
     * @param userId 禁言用户id
     */
    @GetMapping("/forbidSendMsg")
    public Result forbidSendMsg(HttpServletRequest request, long id, long userId) {

        Result result = new Result();
        try {
            LiveSession session = queryChannelService.findOne(LiveSession.class, id);
            Requires.isTrue(session != null && session.getEndTime() == null, "直播不存在");

            WebUser user = Securitys.user(request);
            Requires.isTrue(user.getLiveType() > 0, "当前用户无权限禁言");

            long anchorId = session.getAnchor().getId();
            if (anchorId == user.getId() || anchorId == user.getAnchor().getId()) {
                IMUtils.forbidSendMsg(session.getImGroupId(), String.valueOf(userId));
                return result.ok();
            }
            return result.fail().setMsg("当前用户无权限禁言");

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[直播禁言异常]", e);
            return result.fail().setMsg("直播禁言异常");
        }
    }

    /**
     * 查看粉丝列表
     */
    @GetMapping("/fans")
    public Result fans(HttpServletRequest request, QueryPageRequest pageRequest, String nickname) {
        Result result = new Result();
        try {

            WebUser anchor = Securitys.user(request);
            Requires.isTrue(anchor.getLiveType() > 0, "无权限查看");

            String hql = "select s.fans from LiveFans s where s.anchor.id = :aid";
            Map<String, Object> params = new HashMap<>();
            params.put("aid", anchor.getLiveType() == 1 ? anchor.getId() : anchor.getAnchor().getId());

            if (StringUtils.isNotBlank(nickname)) {
                hql += " and s.nickname like :nickname";
                params.put("nickname", "%" + nickname + "%");
            }
            hql += " order by s.createTime asc";

            QueryPage<WebUser> page = queryChannelService.findPage(hql, pageRequest.setParams(params), WebUser.class);
            List<Map<String, String>> list = page.getResult().stream()
                    .map(user -> {
                        Map<String, String> map = new HashMap<>();
                        map.put("avatar", user.getRealAvatar(STORE_DOMAIN));
                        map.put("nickname", user.getNickname());
                        map.put("username", user.getUsername());
                        return map;
                    })
                    .collect(toList());

            return result.ok().inject(new QueryPage<>(page.getTotalCount(), list, pageRequest.getPageNo(), pageRequest.getPageSize()));

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[获取粉丝列表异常]", e);
            return result.fail().setMsg("获取数据异常");
        }
    }


    /**
     * 获取当前能发送的最大红包
     *
     * @param id 直播间id
     */
    @GetMapping("/currentGoodsMaxRedPacket")
    public Result currentGoodsMaxRedPacket(long id) {
        Result result = new Result();
        try {
            LiveSession session = queryChannelService.findOne(LiveSession.class, id);
            Requires.isTrue(session != null && session.getEndTime() == null, "直播不存在");
            return result.ok().inject(ImmutableMap.of("money", session.getCurrentMaxRedpacket()));
        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[获取最大红包异常]", e);
            return result.fail().setMsg("获取数据异常");
        }
    }


    /**
     * 单发红包
     *
     * @param id     直播间id
     * @param userId 收红包的用户id
     * @param money  红包金额
     */
    @GetMapping("/sendSingleRedpacket")
    public Result sendSingleRedpacket(HttpServletRequest request, long id, long userId, double money) {
        Result result = new Result();
        try {
            LiveSession session = queryChannelService.findOne(LiveSession.class, id);
            Requires.isTrue(session != null && session.getEndTime() == null, "直播不存在");

            Requires.notNull(session.getCurrentGoods(), "直播商品不存在");
            Requires.isTrue(money <= session.getCurrentMaxRedpacket(), "红包金额不能大于" + session.getCurrentMaxRedpacket());

            WebUser anchor = Securitys.user(request);
            checkRedpacket(session, anchor);

            WebUser user = queryChannelService.findOne(WebUser.class, userId);
            Requires.notNull(user, "用户不存在");

            liveSessionApplication.sendSingleRedpacket(session, user, money);

            return result.ok();

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[单发红包异常]", e);
            return result.fail().setMsg("发送异常");
        }
    }

    /**
     * 发送普通红包
     *
     * @param id  直播间id
     * @param len 红包数量
     */
    @GetMapping("/sendCommonRedpacket")
    public Result sendRedpacket(HttpServletRequest request, long id, int len) {
        Result result = new Result();
        try {
            Requires.isTrue(len > 0, "红包数量必须大于0");
            LiveSession session = queryChannelService.findOne(LiveSession.class, id);
            Requires.isTrue(session != null && session.getEndTime() == null, "直播不存在");
            Requires.notNull(session.getCurrentGoods(), "直播商品不存在");

            WebUser anchor = Securitys.user(request);
            checkRedpacket(session, anchor);

            liveSessionApplication.sendCommonRedpacket(session, len);
            return result.ok();

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[发红包异常]", e);
            return result.fail().setMsg("发送异常");
        }
    }

    /**
     * 发送普通红包
     *
     * @param id  直播间id
     * @param len 红包数量
     */
    @GetMapping("/sendVieRedpacket")
    public Result sendVieRedpacket(HttpServletRequest request, long id, int len) {
        Result result = new Result();
        try {
            Requires.isTrue(len > 0, "红包数量必须大于0");
            LiveSession session = queryChannelService.findOne(LiveSession.class, id);
            Requires.isTrue(session != null && session.getEndTime() == null, "直播不存在");
            Requires.notNull(session.getCurrentGoods(), "直播商品不存在");

            WebUser anchor = Securitys.user(request);
            checkRedpacket(session, anchor);

            liveSessionApplication.sendVieRedpacket(session, len);
            return result.ok();

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[发红包异常]", e);
            return result.fail().setMsg("发送异常");
        }
    }

    /**
     * 校验是否有发红包的权限
     *
     * @param session 直播间
     * @param anchor  当前登录的用户
     */
    private void checkRedpacket(LiveSession session, WebUser anchor) {
        Requires.isTrue(anchor.getLiveType() > 0, "无权限操作");
        if (anchor.getLiveType() == 1) {
            Requires.isTrue(anchor.getId() == session.getAnchor().getId(), "无权限操作");
        } else if (anchor.getLiveType() == 2) {
            Requires.isTrue(anchor.getAnchor().getId() == session.getAnchor().getId(), "无权限操作");
        }
    }

    /**
     * 查询直播间是否有红包
     *
     * @param id 直播间id
     */
    @GetMapping("/queryRedpacket")
    public Result queryRedpacket(HttpServletRequest request, long id) {

        Result result = new Result();
        try {

            LiveSession session = queryChannelService.findOne(LiveSession.class, id);
            Requires.isTrue(session != null && session.getEndTime() == null, "直播不存在");

            WebUser user = Securitys.user(request);

            List<LiveSessionRedpacket> redpackets = queryChannelService.findAll("select r from LiveSessionRedpacket r where r.liveSession.id = :sid and ((r.type = 1 and r.user.id = :uid) or (r.type > 1 and r.endTime > :now and r.sendLen < r.len)) order by type asc, createTime asc",
                    ImmutableMap.of("sid", id, "uid", user.getId(), "now", new Timestamp(System.currentTimeMillis())), LiveSessionRedpacket.class);

            List<Object> list = redpackets.stream()
                    .map(r -> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", r.getId());
                        map.put("type", r.getType());
                        map.put("endTime", r.getEndTime());
                        map.put("price", r.getPrice());
                        return map;
                    })
                    .collect(toList());

            return result.ok().inject(ImmutableMap.of("redpackets", list));

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[查询直播间红包异常]", e);
            return result.fail().setMsg("获取数据异常");
        }
    }


    /**
     * 领取直播间红包
     */
    @GetMapping("/getRedpacket")
    public Result getRedpacket(HttpServletRequest request, long redpacketId) {
        Result result = new Result();
        try {
            LiveSessionRedpacket sessionRedpacket = queryChannelService.findOne(LiveSessionRedpacket.class, redpacketId);
            Requires.notNull(sessionRedpacket, "红包不存在");
            liveSessionApplication.getRedpacket(sessionRedpacket, Securitys.user(request));
            return result.ok();
        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[领取红包异常]", e);
            return result.fail().setMsg("领取异常");
        }
    }

    /**
     * 商品sku详情
     *
     * @param goodsId 商品id
     */
    @RequestMapping(value = "/goodsDetail", method = RequestMethod.GET)
    public Result goodsDetail(long goodsId) {
        Result result = new Result();
        try {

            Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(goodsId), Goods.class);
            Requires.notNull(goods, "商品不存在");
            if (StringUtils.isNotBlank(goods.getDefaultImage())) {
                goods.setDefaultImage(STORE_DOMAIN + "/uploads/" + goods.getDefaultImage());
            }

            Map<String, Object> map = new TreeMap<>();
            map.put("name", goods.getName());
            map.put("defaultImage", goods.getDefaultImage());
            map.put("defaultPrice", goods.getDefaultPrice());
            map.put("store", goods.getStore());
            map.put("skus", goods.getSkus());
            map.put("saleAttributes", goods.getSaleAttributes());

            return result.ok().inject(map);

        } catch (IllegalArgumentException e) {
            return result.fail().setMsg(e.getMessage());
        } catch (Exception e) {
            log.error("[获取商品sku异常]", e);
            return result.fail().setMsg("获取数据异常");
        }
    }

}
